<template>
  <div>
    <el-dialog
        :visible.sync="dialogVisible"
        width="30%"
        :title="title + '商品'"
    >
      <el-form
          :model="goodsInfo"
          :rules="rules"
          ref="supplierForm"
          label-width="0"
      >
        <el-form-item prop="goodsName">
          <div style="display: flex">
            <p style="width: 90px; text-align: center; font-weight: bold">
              名称：
            </p>
            <el-input
                size="small"
                clearable
                v-model="goodsInfo.goodsName"
                placeholder="请输入"
            >
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="bakingIdSelect">
          <div style="display: flex">
            <p style="width: 90px; text-align: center; font-weight: bold">
              分类：
            </p>
            <el-cascader
                size="small"
                :props="{
                children: 'bakingList',
              }"
                style="width: 100%"
                v-model="goodsInfo.bakingIdSelect"
                :options="baking"
            >
            </el-cascader>
          </div>
        </el-form-item>
        <div class="row-tow">
          <el-form-item prop="spec">
            <div style="display: flex">
              <p style="width: 60px; text-align: right; font-weight: bold">
                规格：
              </p>
              <el-input
                  size="small"
                  style="width: 130px; margin-left: 16px"
                  clearable
                  v-model="goodsInfo.spec"
                  placeholder="请输入"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="goodsPreparationTime">
            <div
                style="
                display: flex;
                justify-content: flex-end;
                align-items: center;
              "
            >
              <p style="width: 90px; text-align: center; font-weight: bold">
                定制周期：
              </p>
              <el-input-number
                  size="small"
                  v-model="goodsInfo.goodsPreparationTime"
              ></el-input-number
              >
              <span style="color: red; font-size: 10px">分钟</span>
            </div>
          </el-form-item>
        </div>
        <div class="row-tow">
          <el-form-item prop="price">
            <div style="display: flex">
              <p style="width: 63px; text-align: right; font-weight: bold">
                零售价：
              </p>
              <el-input-number
                  size="small"
                  style="width: 130px; margin-left: 13px"
                  v-model="goodsInfo.price"
              ></el-input-number>
            </div>
          </el-form-item>
          <el-form-item prop="costPrice">
            <div
                style="
                display: flex;
                justify-content: flex-end;
                align-items: center;
                margin-right: 20px;
              "
            >
              <p style="width: 79px; text-align: center; font-weight: bold">
                成本价：
              </p>
              <el-input-number
                  size="small"
                  v-model="goodsInfo.costPrice"
              ></el-input-number>
            </div>
          </el-form-item>
        </div>
        <el-form-item prop="goodsImgArray">
          <div style="display: flex">
            <p style="width: 73px; text-align: center; font-weight: bold">
              缩略图：
            </p>
            <!-- <rayUpload @url="getImageUrl"></rayUpload> -->
            <Uploader
                @change="imgChange($event, 1)"
                :limit="1"
                :value="goodsInfo.goodsImgArray"
            ></Uploader>
          </div>
        </el-form-item>
        <el-form-item prop="detailImg">
          <div style="display: flex">
            <p style="width: 73px; text-align: center; font-weight: bold">
              详情图：
            </p>
            <!-- <rayUpload @url="getImageUrl"></rayUpload> -->
            <Uploader
                @change="imgChange($event, 2)"
                :limit="4"
                :value="goodsInfo.detailImg"
            ></Uploader>
          </div>
        </el-form-item>
        <div style="margin-top: 20px; text-align: center">
          <el-button
              @click="dialogVisible = false"
              style="
              background-color: #f3f6fd;
              color: #303e9d;
              width: 100px;
              height: 40px;
              font-weight: bold;
              font-size: 14px;
            "
              size="small"
          >取 消
          </el-button>
          <el-button
              @click="_submit"
              style="
              background-color: #303e9d;
              color: #eeeeee;
              width: 100px;
              height: 40px;
              font-weight: bold;
              font-size: 14px;
            "
              size="small"
          >保 存
          </el-button>
        </div>
      </el-form>
      <!--      <span slot="footer">-->
      <!--        <el-button @click="dialogVisible=false">取 消</el-button>-->
      <!--        <el-button style="background-color:#303e9d;color: #eeeeee" @click="_submit">确 定</el-button>-->
      <!--      </span>-->
    </el-dialog>
  </div>
</template>

<script>
// const Uploader1 = () => import('@/components/Element/Uploader.vue')
// const Uploader2 = () => import('@/components/Element/Uploader.vue')
// import rayUpload from '@/RayComponents/rayUpload.vue'
import Uploader from '@/components/Element/Uploader.vue'

export default {
  name: 'dialogGoods',
  components: {Uploader},
  data() {
    return {
      dialogVisibleGoods: false,
      dialogVisible: false,
      supplierDialog: false,
      title: '',
      userName: '',
      phoneNum: '',

      baking: [],

      goodsInfo: {
        goodsId: null,
        goodsName: '',
        bakingId: '',
        bakingIdSelect: '',
        goodsPreparationTime: 0, //	商品制作时间(分钟)
        spec: '',
        price: 0,
        costPrice: 0,
        goodsImg: '', //缩略图
        goodsImgArray: [],
        detailImg: [], //详情图
      },
      brandList: [],
      recordInfo: {},
      recordId: '',
      storeId: '',
      supplierData: [],
      supplierList: [],
      rules: {
        goodsName: [
          {required: true, message: '请输入商品名称', trigger: 'blur'},
        ],
        bakingIdSelect: [
          {required: true, message: '请选择分类', trigger: 'change'},
        ],
        spec: [{required: true, message: '请输入规格', trigger: 'blur'}],
        detailImg: [
          {required: true, message: '请上传详情图', trigger: 'change'},
        ],
        // storeType: [
        //   { required: true, message: '请选择门店类型', trigger: 'change' },
        // ],
        // storePhone: [
        //   { required: true, message: '请输入门店电话', trigger: 'blur' },
        //   {
        //     pattern: /^1[3-9]\d{9}$/,
        //     message: '请输入有效的手机号码',
        //     trigger: 'blur',
        //   },
        // ],
        // franchiseeId: [
        //   { required: true, message: '请选择加盟商', trigger: 'change' },
        // ],
        // brandPartyId: [
        //   { required: true, message: '请选择品牌方', trigger: 'change' },
        // ],
        // storeArea: [
        //   { required: true, message: '请输入门店面积', trigger: 'blur' },
        //   {
        //     validator(rule, value, callback) {
        //       const num = parseFloat(value)
        //       if (!/^\d+(\.\d{1,2})?$/.test(value)) {
        //         return callback(new Error('请输入合法的正数（最多两位小数）'))
        //       }
        //       if (num <= 0) {
        //         return callback(new Error('面积必须大于 0'))
        //       }
        //       callback()
        //     },
        //     trigger: 'blur',
        //   },
        // ],
      },
    }
  },
  mounted() {
    this.getCategoryList()
  },
  methods: {
    getCategoryList() {
      this.$api.bakingGetCategoryList().then((res) => {
        console.log('获取商品分类', res)
        const finallyDataList = res
        if (finallyDataList.length) {
          finallyDataList.forEach((item) => {
            item.label = item.categoryName
            item.value = item.categoryId
            if (item.bakingList.length) {
              item.bakingList.forEach((sitem) => {
                sitem.label = sitem.bakingName
                sitem.value = sitem.bakingId
              })
            }
          })
        }
        this.baking = finallyDataList
      })
    },
    imgChange(e, type) {
      console.log('上传图片数组', e, type, this.goodsInfo)
      // this.goodsInfo.goodsImgArray = e
      if (type === 1) {
        if (!e.length) {
          this.goodsInfo.goodsImg = ''
        }
        this.goodsInfo.goodsImgArray = e
      } else {
        if (this.title == '录入') {
          this.goodsInfo.detailImg = []
        }
        this.goodsInfo.detailImg = [...e]
      }
    },
    getImageUrl(e) {
      console.log('上传完毕', e)
    },
    handleOpen(val) {
      this.goodsInfo = this.$options.data.call(this).goodsInfo
      this.dialogVisible = true
      if (val) {
        this.title = '编辑'
        Object.keys(this.goodsInfo).forEach((key) => {
          if (val.hasOwnProperty(key)) {
            this.goodsInfo[key] = val[key]
          }
        })
        if (val.image) {
          this.goodsInfo.goodsImgArray = [val.image]
          this.goodsInfo.goodsImg = val.image
        }
        this.goodsInfo.bakingIdSelect = [val.categoryId, val.bakingId]
        console.log('this.goodsInfo.', this.goodsInfo)
      } else {
        this.title = '录入'

        this.$nextTick(() => {
          this.$refs.supplierForm?.clearValidate?.() // 清除校验状态
        })
      }
      //   this.$api.storeGetBrandPartyVoById().then((res) => {
      //     this.brandList = res
      //   })
      //   this.$api.storeGetFranchiseeByName().then((res) => {
      //     this.supplierList = res
      //   })
    },
    openEarth() {
      this.$refs.initMapD.handleOpen()
    },
    receiveMessage(data) {
      this.goodsInfo.address = data.address
      this.goodsInfo.lat = data.latitude
      this.goodsInfo.lon = data.longitude
    },
    async chooseS() {
      //   const supplierData = await this.$api
      //     .franchiseeGetFranchiseeList({ pageSize: 10000, pageNum: 1 })
      //     .then()
      this.supplierData = supplierData.data
      this.userName = ''
      this.phoneNum = ''
      this.supplierDialog = true
    },
    async _submit() {
      this.$refs.supplierForm.validate(async (valid) => {
        if (!valid) return false
        try {
          if (!this.goodsInfo.goodsImgArray.length) {
            return this.$message.error('请上传缩略图!')
          } else {
            this.goodsInfo.goodsImg = this.goodsInfo.goodsImgArray[0]
          }
          this.goodsInfo.bakingId = this.goodsInfo.bakingIdSelect[1]
          const apiMap = {
            录入: this.$api.goodsAddGoods,
            编辑: this.$api.goodsUpdateGoods,
          }
          const apiFunc = apiMap[this.title]
          if (!apiFunc) return
          const resDate = await apiFunc(this.goodsInfo)
          console.log('结果新增', resDate)
          if (resDate == 1) {
            this.$message.success(`${this.title}成功！`)
            this.dialogVisible = false
            this.$emit('addStatus', 1)
          }
        } catch (err) {
          console.error('接口请求出错：', err)
          this.$message.error('操作失败，请稍后重试')
        }
      })
    },

    handleSelectionChange(row) {
      this.recordInfo = row[0]
    },
    comfirm() {
      this.goodsInfo.franchiseeId = this.recordInfo.franchiseeName
      this.goodsInfo.storePhone = this.recordInfo.franchiseePhone
      this.recordId = this.recordInfo.franchiseeId
      this.supplierDialog = false
    },
    resetForm() {
      this.$refs.supplierForm.resetFields()
      this.recordId = ''
    },
  },
}
</script>
<style scoped>
/deep/ .img-item {
  width: 60px !important;
  height: 60px !important;
}

/deep/ .el-upload--picture-card {
  width: 60px !important;
  height: 60px !important;
}

/deep/ .img-wrap .close {
  top: -10px !important;
  font-size: 20px !important;
}

.row-tow {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 0;
  /* display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row; */
}

::v-deep .el-input__inner {
  border-top-left-radius: 0 !important;
  border-bottom-left-radius: 0 !important;
}

/deep/ .el-dialog__title {
  color: #fff;
}

/deep/ .el-dialog {
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

/deep/ .el-dialog__header {
  background-color: #303e9d;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  /*border-top-left-radius: 20 px;*/
  /*/ / border-top-right-radius: 20 px;*/
}
</style>
